<?php
/**
 * FileName: ChineseFirstCharter.php
 * Author: Fei.Song
 * Date: 2021/6/7 14:24
 * Created by PhpStorm
 * Desc:
 */

namespace App\Lib;

class ChineseFirstCharter {
    public function getFirstCharters($string) {
        $text = '';
        $string1 = iconv('UTF-8', 'GBK', $string);
        $string2 = iconv('GBk', 'UTF-8', $string1);
        if ($string2 == $string) {
            $string = $string1;
        }
        for ($i = 0; $i < strlen($string); ++$i) {
            $string1 = substr($string, $i, 1);
            $asc = ord($string1);
            if ($asc > 160) {
                $string2 = substr($string, $i++, 2);
                $text .= $this->getFirstCharter($string2);
            } else {
                $text .= $this->getCharterByASCII(-rand(11055, 20319));
            }
            if (mb_strlen($text, 'utf-8') >= 200) {
                return $text;
            }
        }

        return $text;
    }

    protected function getFirstCharter($str) {
        if (empty($str)) {
            return '';
        }
        $char = ord($str[0]);
        if (($char >= ord('A') && $char <= ord('z')) || ($char >= ord('0') && $char <= ord('9'))) {
            return strtoupper($str[0]);
        }
        $asc = ord($str[0]) * 256 + ord($str[1]) - 65536;

        return $this->getCharterByASCII($asc);
    }

    protected function getCharterByASCII($asc) {
        $charterArr = [
            'A' => [-20319, -20284],
            'B' => [-20283, -19776],
            'C' => [-19775, -19219],
            'D' => [-19218, -18711],
            'E' => [-18710, -18527],
            'F' => [-18526, -18240],
            'G' => [-18239, -17923],
            'H' => [-17922, -17418],
            'J' => [-17417, -16475],
            'K' => [-16474, -16213],
            'L' => [-16212, -15641],
            'M' => [-15640, -15166],
            'N' => [-15165, -14923],
            'O' => [-14922, -14915],
            'P' => [-14914, -14631],
            'Q' => [-14630, -14150],
            'R' => [-14149, -14091],
            'S' => [-14090, -13319],
            'T' => [-13318, -12839],
            'W' => [-12838, -12557],
            'X' => [-12556, -11848],
            'Y' => [-11847, -11056],
            'Z' => [-11055, -10247],
        ];
        foreach ($charterArr as $key => $item) {
            if ($asc >= $item[0] && $asc <= $item[1]) {
                return $key;
            }
        }

        return $this->getCharterByASCII(-rand(11055, 20319));
    }
}
